import React, { useState, useEffect, useCallback } from "react";
import {
  Table,
  Input,
  Button,
  Space,
  message,
  Select,
  Modal,
} from "antd";
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import CommonFormModal from "../../components/CommonFormModal";
import { useFormModal } from "../../hooks/useFormModal";
import { warehouseAreaFormConfig } from "../../utils/formConfigs";

// API基础URL
const API_BASE_URL = "http://localhost:3000";

const { Search } = Input;
const { Option } = Select;

// 库区数据接口定义
interface WarehouseArea {
  key: string;
  id: string;
  code: string;
  name: string;
  warehouseName: string;
  creator: string;
  createTime: string;
  modifier: string;
  modifyTime: string;
}

// 后端库区数据接口定义
interface ReservoirItem {
  id: number;
  code: string;
  name: string;
  warehouseId: number;
  warehouseCode: string;
  affiliated: string;
  add: string;
  addtime: string;
  edit: string;
  edittime: string;
}

// 仓库选项接口定义
interface WarehouseOption {
  id: number;
  code: string;
  name: string;
}


export default function WarehouseAreaManagement() {
  const [warehouseAreaData, setWarehouseAreaData] = useState<WarehouseArea[]>([]);
  const [warehouseOptions, setWarehouseOptions] = useState<WarehouseOption[]>([]);
  const [searchParams, setSearchParams] = useState({
    areaCode: "",
    areaName: "",
    warehouse: undefined, // 修改为undefined，使Select正确显示placeholder
  });
  const [selectedRows, setSelectedRows] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);

  // 使用通用表单Hook
  const {
    visible,
    isAddMode,
    currentRecord,
    loading: formLoading,
    openAddModal,
    openEditModal,
    closeModal,
  } = useFormModal<WarehouseArea>();

  // 数据转换函数：将后端数据转换为前端需要的格式
  const transformReservoirData = (reservoirData: ReservoirItem[]): WarehouseArea[] => {
    return reservoirData.map((item) => ({
      key: item.id.toString(),
      id: item.id.toString(),
      code: item.code,
      name: item.name,
      warehouseName: item.affiliated,
      creator: item.add,
      createTime: item.addtime,
      modifier: item.edit,
      modifyTime: item.edittime,
    }));
  };

  // 获取库区列表
  const fetchReservoirData = useCallback(async () => {
    try {
      setLoading(true);
      const response = await fetch(`${API_BASE_URL}/api/reservoir`);
      if (!response.ok) {
        throw new Error('获取库区数据失败');
      }
      const data: ReservoirItem[] = await response.json();
      const transformedData = transformReservoirData(data);
      setWarehouseAreaData(transformedData);
    } catch (error) {
      message.error('获取库区数据失败');
      console.error('Error fetching reservoir data:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  // 获取仓库选项
  const fetchWarehouseOptions = async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/warehouse`);
      if (!response.ok) {
        throw new Error('获取仓库数据失败');
      }
      const data = await response.json();
      setWarehouseOptions(data);
    } catch (error) {
      message.error('获取仓库数据失败');
      console.error('Error fetching warehouse options:', error);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchReservoirData();
    fetchWarehouseOptions();
  }, [fetchReservoirData]);

  // 处理搜索
  const handleSearch = () => {
    // 重新获取数据并应用搜索条件
    fetchReservoirData().then(() => {
      const filteredData = warehouseAreaData.filter((item) => {
        return (
          (searchParams.areaCode === "" ||
            item.code.includes(searchParams.areaCode)) &&
          (searchParams.areaName === "" ||
            item.name.includes(searchParams.areaName)) &&
          (searchParams.warehouse === undefined ||
            item.warehouseName === searchParams.warehouse)
        );
      });
      setWarehouseAreaData(filteredData);
      message.success(`找到 ${filteredData.length} 条匹配记录`);
    });
  };

  // 处理重置
  const handleReset = () => {
    setSearchParams({
      areaCode: "",
      areaName: "",
      warehouse: undefined, // 重置为undefined
    });
    fetchReservoirData(); // 重新获取所有数据
    message.info("已重置搜索条件");
  };

  // 处理新增库区
  const handleAddArea = () => {
    openAddModal();
  };

  // 处理编辑库区
  const handleEdit = (record: WarehouseArea) => {
    openEditModal(record);
  };

  // 删除库区
  const deleteReservoir = async (id: string) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/reservoir/${id}`, {
        method: 'DELETE',
      });

      if (!response.ok) {
        throw new Error('删除库区失败');
      }

      await fetchReservoirData(); // 重新获取数据
      return true;
    } catch (error) {
      message.error('删除库区失败');
      console.error('Error deleting reservoir:', error);
      return false;
    }
  };

  // 确认删除
  const handleDelete = (record: WarehouseArea) => {
    Modal.confirm({
      title: "确认删除",
      content: `确定要删除库区 "${record.name}" 吗？此操作不可撤销。`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        const success = await deleteReservoir(record.id);
        if (success) {
          message.success(`库区 "${record.name}" 已删除`);
        }
      },
    });
  };

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRows.length === 0) {
      message.warning("请先选择要删除的库区");
      return;
    }

    Modal.confirm({
      title: "批量删除",
      content: `确定要删除选中的 ${selectedRows.length} 个库区吗？此操作不可撤销。`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        let successCount = 0;
        for (const id of selectedRows) {
          const success = await deleteReservoir(id);
          if (success) {
            successCount++;
          }
        }
        
        if (successCount > 0) {
          await fetchReservoirData(); // 重新获取数据
          setSelectedRows([]); // 清空选中行
          message.success(`已删除 ${successCount} 个库区`);
        }
      },
    });
  };

  // 新增库区
  const createReservoir = async (values: Record<string, unknown>) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/reservoir`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          code: values.code,
          name: values.name,
          affiliated: values.warehouse,
          add: 'admin',
          addtime: new Date().toISOString().split('T')[0],
          edit: 'admin',
          edittime: new Date().toISOString().split('T')[0],
        }),
      });

      if (!response.ok) {
        throw new Error('新增库区失败');
      }

      await fetchReservoirData(); // 重新获取数据
      message.success(`库区 "${values.name}" 已创建`);
    } catch (error) {
      message.error('新增库区失败');
      console.error('Error creating reservoir:', error);
    }
  };

  // 更新库区
  const updateReservoir = async (id: string, values: Record<string, unknown>) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/reservoir/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          code: values.code,
          name: values.name,
          affiliated: values.warehouse,
          edit: 'admin',
          edittime: new Date().toISOString().split('T')[0],
        }),
      });

      if (!response.ok) {
        throw new Error('更新库区失败');
      }

      await fetchReservoirData(); // 重新获取数据
      message.success(`库区 "${values.name}" 已更新`);
    } catch (error) {
      message.error('更新库区失败');
      console.error('Error updating reservoir:', error);
    }
  };

  // 处理表单提交
  const handleSubmit = async (values: Record<string, unknown>, isAddMode: boolean, currentRecord?: WarehouseArea | null) => {
    if (isAddMode) {
      await createReservoir(values);
    } else {
      if (currentRecord) {
        await updateReservoir(currentRecord.id, values);
      }
    }
  };

  // 表格列配置
  const columns = [
    {
      title: "",
      dataIndex: "checkbox",
      key: "checkbox",
      width: 40,
      render: (_: unknown, record: WarehouseArea) => (
        <Input
          type="checkbox"
          checked={selectedRows.includes(record.id)}
          onChange={(e) => {
            if (e.target.checked) {
              setSelectedRows([...selectedRows, record.id]);
            } else {
              setSelectedRows(selectedRows.filter((id) => id !== record.id));
            }
          }}
        />
      ),
    },
    {
      title: "id",
      dataIndex: "id",
      key: "id",
      render: (text: string) => <a href="#">{text}</a>,
    },
    {
      title: "编码",
      dataIndex: "code",
      key: "code",
    },
    {
      title: "库区名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "所属仓库",
      dataIndex: "warehouseName",
      key: "warehouseName",
    },
    {
      title: "创建人",
      dataIndex: "creator",
      key: "creator",
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
    },
    {
      title: "修改人",
      dataIndex: "modifier",
      key: "modifier",
      render: (text: string) => <a href="#">{text}</a>,
    },
    {
      title: "修改时间",
      dataIndex: "modifyTime",
      key: "modifyTime",
      render: (text: string) => <a href="#">{text}</a>,
    },
    {
      title: "操作",
      key: "operation",
      render: (_: unknown, record: WarehouseArea) => (
        <Space size="small">
          <a
            href="#"
            onClick={(e) => {
              e.preventDefault();
              handleEdit(record);
            }}
          >
            <EditOutlined /> 编辑
          </a>
          <a
            href="#"
            onClick={(e) => {
              e.preventDefault();
              handleDelete(record);
            }}
          >
            <DeleteOutlined /> 删除
          </a>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: "24px" }}>
      {/* 搜索区域 */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          marginBottom: "24px",
          flexWrap: "wrap",
        }}
      >
        <Search
          placeholder="请输入库区编号"
          allowClear
          enterButton={<SearchOutlined />}
          value={searchParams.areaCode}
          onChange={(e) =>
            setSearchParams({ ...searchParams, areaCode: e.target.value })
          }
          onSearch={handleSearch}
          style={{ width: 200, marginRight: 16, marginBottom: 8 }}
        />
        <Search
          placeholder="请输入库区名称"
          allowClear
          enterButton={<SearchOutlined />}
          value={searchParams.areaName}
          onChange={(e) =>
            setSearchParams({ ...searchParams, areaName: e.target.value })
          }
          onSearch={handleSearch}
          style={{ width: 200, marginRight: 16, marginBottom: 8 }}
        />
        <Select
          placeholder="请选择仓库"
          style={{ width: 200, marginRight: 16, marginBottom: 8 }}
          value={searchParams.warehouse}
          onChange={(value) =>
            setSearchParams({ ...searchParams, warehouse: value })
          }
          showSearch
          optionFilterProp="children"
        >
          {warehouseOptions.map((option) => (
            <Option key={option.id} value={option.name}>
              {option.name}
            </Option>
          ))}
        </Select>
        <Button
          type="primary"
          style={{ marginRight: 8, marginBottom: 8 }}
          onClick={handleSearch}
        >
          搜索
        </Button>
        <Button onClick={handleReset} style={{ marginBottom: 8 }}>
          重置
        </Button>
      </div>

      {/* 按钮区域 */}
      <div style={{ marginBottom: "24px", display: "flex" }}>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAddArea}>
          新增库区
        </Button>
        {selectedRows.length > 0 && (
          <Button danger style={{ marginLeft: 16 }} onClick={handleBatchDelete}>
            批量删除
          </Button>
        )}
      </div>

      {/* 表格 */}
      <Table
        dataSource={warehouseAreaData}
        columns={columns}
        bordered
        rowKey="id"
        pagination={{ pageSize: 10 }}
        loading={loading}
      />

      {/* 通用表单弹窗 */}
      <CommonFormModal
        visible={visible}
        title={isAddMode ? "新增库区" : "编辑库区"}
        isAddMode={isAddMode}
        currentRecord={currentRecord}
        formItems={warehouseAreaFormConfig}
        onSubmit={handleSubmit as unknown as (values: WarehouseArea, isAddMode: boolean, currentRecord?: WarehouseArea | null) => void | Promise<void>}
        onCancel={closeModal}
        loading={formLoading}
        width={600}
      />
    </div>
  );
}
